package com.toycloud.system.service.impl.business;

import java.util.*;
import java.util.stream.Collectors;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.toycloud.business.dto.params.business.AssociationDemandParams;
import com.toycloud.business.dto.params.business.FeedbackApplicationVersionManagerParams;
import com.toycloud.business.dto.results.CommonResult;
import com.toycloud.business.service.IDemandRecordService;
import com.toycloud.common.core.utils.DateUtils;
import com.toycloud.common.core.utils.StringUtils;
import com.toycloud.common.core.utils.uuid.IdUtils;
import com.toycloud.common.core.web.domain.AjaxResult;
import com.toycloud.system.mapper.business.FeedbackProductVersionManagerMapper;
import com.toycloud.system.utils.FileUrlUtils;
import com.toycloud.system.domain.business.*;
import com.toycloud.system.domain.feedback.FeedbackConfig;
import com.toycloud.system.mapper.business.FeedbackApplicationVersionManagerDetailMapper;
import com.toycloud.system.mapper.business.FeedbackApplicationVersionManagerMapper;
import com.toycloud.system.mapper.business.FeedbackProductVersionManagerDetailMapper;
import com.toycloud.system.service.business.IFeedbackApplicationVersionManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


/**
 * 应用版本管理Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-18
 */
@Service
public class FeedbackApplicationVersionManagerServiceImpl implements IFeedbackApplicationVersionManagerService
{
    @Resource
    private FeedbackApplicationVersionManagerMapper feedbackApplicationVersionManagerMapper;
    @Resource
    private FeedbackProductVersionManagerMapper feedbackProductVersionManagerMapper;
    @Resource
    private FeedbackApplicationVersionManagerDetailMapper feedbackApplicationVersionManagerDetailMapper;
    @Resource
    private FeedbackProductVersionManagerDetailMapper feedbackProductVersionManagerDetailMapper;
    @Autowired
    private IDemandRecordService iDemandRecordService;

    /**
     * 查询应用版本管理
     *
     * @param id 应用版本管理主键
     * @return 应用版本管理
     */
    @Override
    public FeedbackApplicationVersionManager selectFeedbackApplicationVersionManagerById(String id)
    {
        FeedbackApplicationVersionManager feedbackApplicationVersionManager = feedbackApplicationVersionManagerMapper.selectFeedbackApplicationVersionManagerById(id);
        List<AssociationDemandParams> list = feedbackApplicationVersionManagerDetailMapper.getDemandsByParentId(feedbackApplicationVersionManager.getId());
        list.stream().forEach(item->{
            item.setDemandContent(FileUrlUtils.stripHtmlTags(item.getDemandContent()));
        });
        feedbackApplicationVersionManager.setAssociationDemandParams(list);
        return feedbackApplicationVersionManager;
    }

    /**
     * 查询应用版本管理列表
     *
     * @param feedbackApplicationVersionManagerParams 应用版本管理
     * @return 应用版本管理
     */
    @Override
    public CommonResult<List<FeedbackApplicationVersionManager>> selectFeedbackApplicationVersionManagerList(FeedbackApplicationVersionManagerParams feedbackApplicationVersionManagerParams)
    {
        if (feedbackApplicationVersionManagerParams.getApplicationids() == null) {
            feedbackApplicationVersionManagerParams.setApplicationids(new ArrayList<>());
        }
        if (feedbackApplicationVersionManagerParams.getApplicationversions() == null) {
            feedbackApplicationVersionManagerParams.setApplicationversions(new ArrayList<>());
        }

        Set<String> resultSet = new LinkedHashSet<>(); // 使用LinkedHashSet保持插入顺序同时去重

        if(feedbackApplicationVersionManagerParams.getAppVersion()!=null) {
            for (List<String> pair : feedbackApplicationVersionManagerParams.getAppVersion()) {
                if(pair.size() >= 2){ // 确保pair至少有两个元素
                    String first = pair.get(0);
                    String second = pair.get(1);

                    // 构建所需格式的字符串并添加到集合中
                    resultSet.add(first + "-" + second);

                    // 如果需要更新applicationids和applicationversions列表，可以在这里进行
                    if (!feedbackApplicationVersionManagerParams.getApplicationids().contains(first)) {
                        feedbackApplicationVersionManagerParams.getApplicationids().add(first);
                    }
                    feedbackApplicationVersionManagerParams.getApplicationversions().add(second);
                } else if (pair.size() == 1) { // 处理只有一个元素的情况
                    String first = pair.get(0);
                    resultSet.add(first); // 这种情况可能不符合你的需求，可以根据实际情况调整
                    if (!feedbackApplicationVersionManagerParams.getApplicationids().contains(first)) {
                        feedbackApplicationVersionManagerParams.getApplicationids().add(first);
                    }
                }
            }
        }

// 将resultSet转换为List<String>
        List<String> result = new ArrayList<>(resultSet);
        feedbackApplicationVersionManagerParams.setApplicationids(result);

        //根据childrernid查出对应的应用id数组
        if (feedbackApplicationVersionManagerParams.getChildrenid() != null) {
            // 初始化 applicationids 列表
            List<String> applicationids = feedbackApplicationVersionManagerDetailMapper.getApplicationidsByChildrenid(feedbackApplicationVersionManagerParams.getChildrenid());
            feedbackApplicationVersionManagerParams.setIds(applicationids);
        } else {
            feedbackApplicationVersionManagerParams.setIds(new ArrayList<>());
        }

        List<List<String>> modelType = feedbackApplicationVersionManagerParams.getModelType();
        if (modelType != null) {
            // 查询出 feedbackproductversionmanager 表的 id, 再根据 id 查询出 feedbackproductversionmanagerdetail 的 applicationid 变成 string 数组

            // 获取已经设置的 applicationids
            List<String> existingIds = feedbackApplicationVersionManagerParams.getIds();

            // 创建一个映射，用于快速查找
            List<FeedbackProductVersionManager> versionList = feedbackProductVersionManagerMapper.list();
            Map<String, List<String>> idMap = versionList.stream()
                    .collect(Collectors.groupingBy(app ->
                                    app.getProducttypeid() + "," + app.getProductmodelid() + "," + app.getModelversion(),
                            Collectors.mapping(FeedbackProductVersionManager::getId, Collectors.toList())
                    ));

            List<String> filteredIds = new ArrayList<>();
            for (List<String> item : modelType) {
                // 构建键时只考虑实际存在的元素
                String key = String.join(",", item.stream().map(Object::toString).toArray(String[]::new));
                if (idMap.containsKey(key)) {
                    filteredIds.addAll(idMap.get(key));
                }
            }

            // 根据 filteredIds 查询对应的 applicationids 并添加到 existingIds 中
            List<FeedbackProductVersionManagerDetail> list = feedbackProductVersionManagerDetailMapper.list();
            System.out.println(list);
            List<String> additionalApplicationids = feedbackProductVersionManagerDetailMapper.list().stream()
                    .filter(detail -> filteredIds.contains(detail.getParentid()))
                    .map(FeedbackProductVersionManagerDetail::getApplicationid)
                    .collect(Collectors.toList());


            // 将新获取的 applicationids 添加到 existingIds 中，避免重复
            Set<String> uniqueIds = new LinkedHashSet<>(existingIds); // 使用 LinkedHashSet 保持插入顺序并去重
            uniqueIds.addAll(additionalApplicationids);
            if(feedbackApplicationVersionManagerParams.getModelType().size()!=0&&uniqueIds.size()==0){
                uniqueIds.add("0");
            }

            // 更新 feedbackApplicationVersionManagerParams 的 ids
            feedbackApplicationVersionManagerParams.setIds(new ArrayList<>(uniqueIds));
        }

        PageHelper.startPage(feedbackApplicationVersionManagerParams.getCurrent(), feedbackApplicationVersionManagerParams.getPageSize());
        List<FeedbackApplicationVersionManager> feedbackApplicationVersionManagers = feedbackApplicationVersionManagerMapper.selectFeedbackApplicationVersionManagerList(feedbackApplicationVersionManagerParams);
        List<OptionVO> optionVOS = feedbackApplicationVersionManagerMapper.selectApplicationOption();
        List<FeedbackProductVersionManagerDetail> list = feedbackProductVersionManagerDetailMapper.list();
        feedbackApplicationVersionManagers.stream().forEach(item->{
            item.setApplicationname(optionVOS.stream().filter(item1->item1.getId().equals(item.getApplicationid())).findFirst().get().getName());
            item.setProductversion(list.stream().filter(Objects::nonNull).filter(item1->item1.getApplicationid().equals(item.getId())).map(FeedbackProductVersionManagerDetail::getProductversion).collect(Collectors.joining(",")));
        });
        Page<FeedbackApplicationVersionManager> feedbackApplicationVersionManagersPage = (Page<FeedbackApplicationVersionManager>) feedbackApplicationVersionManagers;
        return CommonResult.Success((int) feedbackApplicationVersionManagersPage.getTotal(), feedbackApplicationVersionManagers);
    }
    @Override
    public CommonResult<List<FeedbackApplicationVersionManager>> export(FeedbackApplicationVersionManagerParams feedbackApplicationVersionManagerParams)
    {
        //根据childrernid查出对应的应用id数组
        if (feedbackApplicationVersionManagerParams.getChildrenid() != null) {
            // 初始化 applicationids 列表
            List<String> applicationids = feedbackApplicationVersionManagerDetailMapper.getApplicationidsByChildrenid(feedbackApplicationVersionManagerParams.getChildrenid());
            feedbackApplicationVersionManagerParams.setIds(applicationids);
        } else {
            feedbackApplicationVersionManagerParams.setIds(new ArrayList<>());
        }

        List<List<String>> modelType = feedbackApplicationVersionManagerParams.getModelType();
        if (modelType != null) {
            // 查询出 feedbackproductversionmanager 表的 id, 再根据 id 查询出 feedbackproductversionmanagerdetail 的 applicationid 变成 string 数组

            // 获取已经设置的 applicationids
            List<String> existingIds = feedbackApplicationVersionManagerParams.getIds();

            // 创建一个映射，用于快速查找
            List<FeedbackProductVersionManager> versionList = feedbackProductVersionManagerMapper.list();
            Map<String, List<String>> idMap = versionList.stream()
                    .collect(Collectors.groupingBy(app ->
                                    app.getProducttypeid() + "," + app.getProductmodelid() + "," + app.getModelversion(),
                            Collectors.mapping(FeedbackProductVersionManager::getId, Collectors.toList())
                    ));

            List<String> filteredIds = new ArrayList<>();
            for (List<String> item : modelType) {
                // 构建键时只考虑实际存在的元素
                String key = String.join(",", item.stream().map(Object::toString).toArray(String[]::new));
                if (idMap.containsKey(key)) {
                    filteredIds.addAll(idMap.get(key));
                }
            }

            // 根据 filteredIds 查询对应的 applicationids 并添加到 existingIds 中
            List<String> additionalApplicationids = feedbackProductVersionManagerDetailMapper.list().stream()
                    .filter(detail -> filteredIds.contains(detail.getParentid()))
                    .map(FeedbackProductVersionManagerDetail::getApplicationid)
                    .collect(Collectors.toList());

            // 将新获取的 applicationids 添加到 existingIds 中，避免重复
            Set<String> uniqueIds = new LinkedHashSet<>(existingIds); // 使用 LinkedHashSet 保持插入顺序并去重
            uniqueIds.addAll(additionalApplicationids);

            // 更新 feedbackApplicationVersionManagerParams 的 ids
            feedbackApplicationVersionManagerParams.setIds(new ArrayList<>(uniqueIds));
        }
        List<FeedbackApplicationVersionManager> feedbackApplicationVersionManagers = feedbackApplicationVersionManagerMapper.selectFeedbackApplicationVersionManagerList(feedbackApplicationVersionManagerParams);
        List<OptionVO> optionVOS = feedbackApplicationVersionManagerMapper.selectApplicationOption();
        List<FeedbackProductVersionManagerDetail> list = feedbackProductVersionManagerDetailMapper.list();
        feedbackApplicationVersionManagers.stream().forEach(item->{
            item.setApplicationname(optionVOS.stream().filter(item1->item1.getId().equals(item.getApplicationid())).findFirst().get().getName());
            item.setProductversion(list.stream().filter(Objects::nonNull).filter(item1->item1.getApplicationid().equals(item.getId())).map(FeedbackProductVersionManagerDetail::getProductversion).collect(Collectors.joining(",")));
        });
        return CommonResult.Success(feedbackApplicationVersionManagers);
    }



    /**
     * 新增应用版本管理
     *
     * @param feedbackApplicationVersionManager 应用版本管理
     * @return 结果
     */
    @Override
    public CommonResult insertFeedbackApplicationVersionManager(FeedbackApplicationVersionManager feedbackApplicationVersionManager)
    {
        String id = IdUtils.simpleUUID();
        feedbackApplicationVersionManager.setCreateTime(DateUtils.getNowDate());
        feedbackApplicationVersionManager.setId(id);
        feedbackApplicationVersionManagerMapper.insertFeedbackApplicationVersionManager(feedbackApplicationVersionManager);
        feedbackApplicationVersionManager.getDemands().forEach(item->{
            FeedbackApplicationVersionManagerDetail item1 = new FeedbackApplicationVersionManagerDetail();
            item1.setParentid(id);
            item1.setDemandid(item);
            item1.setCreateTime(DateUtils.getNowDate());
            feedbackApplicationVersionManagerDetailMapper.insertFeedbackApplicationVersionManagerDetail(item1);
        });
        iDemandRecordService.updateVersion(String.join(",", feedbackApplicationVersionManager.getDemands()));
        return CommonResult.Success();
    }

    /**
     * 修改应用版本管理
     *
     * @param feedbackApplicationVersionManager 应用版本管理
     * @return 结果
     */
    @Override
    public CommonResult updateFeedbackApplicationVersionManager(FeedbackApplicationVersionManager feedbackApplicationVersionManager)
    {
        feedbackApplicationVersionManager.setUpdateTime(DateUtils.getNowDate());
        feedbackApplicationVersionManagerMapper.updateFeedbackApplicationVersionManager(feedbackApplicationVersionManager);
        List<AssociationDemandParams> demandsByParentId = feedbackApplicationVersionManagerDetailMapper.getDemandsByParentId(feedbackApplicationVersionManager.getId());
        Map map = processLists(demandsByParentId.stream().map(item->item.getId()).collect(Collectors.toList()),feedbackApplicationVersionManager.getDemands());
        List<String> addList = (List<String>) map.get("insert");
        List<String> updateList = (List<String>) map.get("update");
        List<String> deleteList = (List<String>) map.get("delete");
        addList.forEach(item->{
            FeedbackApplicationVersionManagerDetail item1 = new FeedbackApplicationVersionManagerDetail();
            item1.setParentid(feedbackApplicationVersionManager.getId());
            item1.setDemandid(item);
            item1.setCreateTime(DateUtils.getNowDate());
            feedbackApplicationVersionManagerDetailMapper.insertFeedbackApplicationVersionManagerDetail(item1);

        });
        updateList.forEach(item->{
            FeedbackApplicationVersionManagerDetail item1 = new FeedbackApplicationVersionManagerDetail();
            item1.setDemandid(item);
            item1.setParentid(feedbackApplicationVersionManager.getId());
            feedbackApplicationVersionManagerDetailMapper.updateByTwo(item1);
        });
        deleteList.forEach(item->{
            feedbackApplicationVersionManagerDetailMapper.deleteFeedbackApplicationVersionManagerDetailByDemandid(item);
        });

        iDemandRecordService.updateVersion(String.join(",", feedbackApplicationVersionManager.getDemands()));
        return CommonResult.Success();
    }
    public static Map processLists(List<String> oldList, List<String> newList) {
        // 将列表转换为集合以便快速查找和操作
        Set<String> setOld = new HashSet<>(oldList);
        Set<String> setNew = new HashSet<>(newList);

        // 需要删除的项（旧数据有但新数据没有）
        List<String> toDelete = new ArrayList<>(setOld);
        toDelete.removeAll(setNew);

        // 新增的项（新数据有但旧数据没有）
        List<String> toAdd = new ArrayList<>(setNew);
        toAdd.removeAll(setOld);

        // 更新的项（交集部分）
        List<String> toUpdate = new ArrayList<>(setOld);
        toUpdate.retainAll(setNew); // 保留共同元素

        // 构建返回的结果Map
        Map<String, List<String>> resultMap = new HashMap<>();
        resultMap.put("delete", toDelete);
        resultMap.put("update", toUpdate);
        resultMap.put("insert", toAdd);

        return resultMap;
    }

    /**
     * 批量删除应用版本管理
     *
     * @param ids 需要删除的应用版本管理主键
     * @return 结果
     */
    @Override
    public int deleteFeedbackApplicationVersionManagerByIds(Long[] ids)
    {
        return feedbackApplicationVersionManagerMapper.deleteFeedbackApplicationVersionManagerByIds(ids);
    }

    /**
     * 删除应用版本管理信息
     *
     * @param id 应用版本管理主键
     * @return 结果
     */
    @Override
    public void deleteFeedbackApplicationVersionManagerById(String id)
    {
        feedbackApplicationVersionManagerMapper.deleteFeedbackApplicationVersionManagerById(id);
    }

    @Override
    public List<OptionVO> selectApplicationOption() {
        return feedbackApplicationVersionManagerMapper.selectApplicationOption();
    }

    @Override
    public CommonResult<List<AssociationDemandParams>> getDemandPage(AssociationDemandParams associationDemandParams) {
        PageHelper.startPage(associationDemandParams.getCurrent(), associationDemandParams.getPageSize());
        //逗号分割转list
        if(StringUtils.isNotEmpty(associationDemandParams.getApplicationLabel())){
            associationDemandParams.setDemandLabels(Arrays.stream(associationDemandParams.getApplicationLabel().split(",")).collect(Collectors.toList()));
        }
        List<AssociationDemandParams> demandList = feedbackApplicationVersionManagerMapper.getDemandPage(associationDemandParams);

        demandList.stream().forEach(item->{
            item.setDemandContent(FileUrlUtils.stripHtmlTags(item.getDemandContent()));
        });
        Page<AssociationDemandParams> demandPage = (Page<AssociationDemandParams>) demandList;
        return CommonResult.Success((int) demandPage.getTotal(), demandList);

    }

    @Override
    public List<FeedbackApplicationVersionManager> getList( ) {
        List<FeedbackApplicationVersionManager> feedbackApplicationVersionManagers = feedbackApplicationVersionManagerMapper.selectFeedbackApplicationVersionManagerList(new FeedbackApplicationVersionManagerParams());
        List<OptionVO> optionVOS = feedbackApplicationVersionManagerMapper.selectApplicationOption();
        List<FeedbackProductVersionManagerDetail> list = feedbackProductVersionManagerDetailMapper.list();
        feedbackApplicationVersionManagers.stream().forEach(item->{
            item.setApplicationname(optionVOS.stream().filter(x->x.getId().equals(item.getApplicationid())).findFirst().get().getName());
            item.setProductversion(list.stream().filter(Objects::nonNull).filter(item1->item1.getApplicationid().equals(item.getId())).map(FeedbackProductVersionManagerDetail::getProductversion).collect(Collectors.joining(",")));
        });
        return feedbackApplicationVersionManagers;
    }
    @Override
    public List<OptionVO> option() {
        List<OptionVO> res = new ArrayList<>();
        List<FeedbackApplicationVersionManager> feedbackApplicationVersionManagers = feedbackApplicationVersionManagerMapper.selectFeedbackApplicationVersionManagerList(new FeedbackApplicationVersionManagerParams());
        List<OptionVO> optionVOS = feedbackApplicationVersionManagerMapper.selectApplicationOption();
        feedbackApplicationVersionManagers.stream().forEach(
                item->{
                    OptionVO optionVO = new OptionVO();
                    optionVO.setId(item.getId());
                    optionVO.setName(optionVOS.stream().filter(x->x.getId().equals(item.getApplicationid())).findFirst().get().getName());
                    res.add(optionVO);
                }
        );
        return res;

    }

    @Override
    public AjaxResult getTree() {//TODO 级联没做
        List<FeedbackConfig> configList = feedbackApplicationVersionManagerMapper.getTree();
        List<FeedbackConfig> typeList = configList.stream().filter(x -> ("10".equals(x.getType()))).collect(Collectors.toList());
        List<FeedbackConfig> modelList = configList.stream().filter(x -> ("2".equals(x.getType()))).collect(Collectors.toList());
        List<FeedbackProductVersionManager> productList = feedbackProductVersionManagerMapper.list();
        Set<String> seen = new HashSet<>();
        List<FeedbackProductVersionManager> distinctList = productList.stream()
                .filter(item -> seen.add(item.getModelversion())) // 去重
                .collect(Collectors.toList());

        List<TreeVO> res = new ArrayList<>();
        typeList.forEach(item->{//1级
            res.add(new TreeVO(item.getName(), item.getId().toString(), item.getPid().toString(), item.getType().toString(), item.getId().toString(), null));
        });
        List<TreeVO> modelList2 = new ArrayList<>();
        modelList.forEach(item->{//2级
            modelList2.add(new TreeVO(item.getName(), item.getId().toString(), item.getPid().toString(), item.getType().toString(), item.getId().toString(), null));
        });
        List<TreeVO> productList2 = new ArrayList<>();
        distinctList.forEach(item->{//三级
            productList2.add(new TreeVO(item.getModelversion(), item.getProducttypeid(), item.getProducttypeid(), "", item.getModelversion(), null));
        });
        //2级插入3级数据
        modelList2.forEach(item->{
            item.setChildren(productList2);
        });

        res.forEach(item->{//1级插入2级数据
            item.setChildren(modelList2);
        });
        return AjaxResult.success(res);
    }

    @Override
    public AjaxResult getAppAndVersionTree() {
        List<TreeVO> list1 = feedbackProductVersionManagerMapper.getAppTree();
        //结果集
        //value label
        //9	知识问答
        //10	报听写
        List<TreeVO> list2 = feedbackProductVersionManagerMapper.getVersionTree();
        //结果集
        //key pid label value
        //878d9eb106a24add951d1092ee74c33f	9	v5	v5
        //8849b7bf01b447e8b68a24d719f13527	9	v3	v3
        //8b76f04da92947b191e8cdfb912e3fbc	10	v2	v2
        //99834e7749ec494bac7fb30f472113a3	10	1	1
        //b41e7736cbdd4e5b8d9e28c2522a10f6	9	v5	v5
        //f7b0bbf0bba74e2ab091c2bccd3e0e58	10	v2	v2

        for (TreeVO item : list1) {
            // 确保每个item都有一个children列表
            if (item.getChildren() == null) {
                item.setChildren(new ArrayList<>());
            }
        }

// 遍历list2，根据pid（list2）和value（list1）匹配，并将子项添加到相应的父项的children列表中
        for (TreeVO child : list2) {
            String pid = child.getPid();
            for (TreeVO parent : list1) {
                if (pid.equals(parent.getValue())) {
                    // 检查parent的children列表是否已经包含相同value的child
                    boolean isDuplicate = false;
                    for (TreeVO existingChild : parent.getChildren()) {
                        if (existingChild.getValue().equals(child.getValue())) {
                            isDuplicate = true;
                            break;
                        }
                    }
                    if (!isDuplicate) {
                        parent.getChildren().add(child);
                    }
                    break; // 找到对应的parent后退出循环
                }
            }
        }

        return AjaxResult.success(list1);
    }
}
